using System.Globalization;

namespace SimulationPathViewer
{
    public class DxfPathExtractor
    {
        public static List<(double X, double Y)> ExtractPathFromDxf(string filePath)
        {
            var pathPoints = new List<(double X, double Y)>();
            var lines = File.ReadAllLines(filePath);

            for (int i = 0; i < lines.Length - 1; i++)
            {
                if (lines[i].Trim() == "LINE")
                {
                    var startPoint = ExtractPoint(lines, ref i);
                    var endPoint = ExtractPoint(lines, ref i);
                    
                    if (startPoint.HasValue)
                        pathPoints.Add(startPoint.Value);
                    if (endPoint.HasValue)
                        pathPoints.Add(endPoint.Value);
                }
            }

            return pathPoints;
        }

        private static (double X, double Y)? ExtractPoint(string[] lines, ref int i)
        {
            double x = 0, y = 0;
            bool hasX = false, hasY = false;

            while (i < lines.Length - 1)
            {
                i++;
                var line = lines[i].Trim();
                
                if (line == "LINE" || string.IsNullOrWhiteSpace(line))
                    break;

                if (line == "10" || line == "11") // X coordinate
                {
                    i++;
                    if (double.TryParse(lines[i].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out double xVal))
                    {
                        x = xVal;
                        hasX = true;
                    }
                }
                else if (line == "20" || line == "21") // Y coordinate
                {
                    i++;
                    if (double.TryParse(lines[i].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out double yVal))
                    {
                        y = yVal;
                        hasY = true;
                    }
                }
            }

            return (hasX && hasY) ? ((double X, double Y))(x, y) : null;
        }
    }
}
